package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.ImMessage;
import com.example.mapper.ImMessageMapper;
import com.example.service.ImMessageService;
import com.example.vo.Result;
import com.example.vo.UserWithLastMessageVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
* @author circle48
* @description 针对表【im_message】的数据库操作Service实现
* @createDate 2024-06-13 15:22:03
*/
@Service
public class ImMessageServiceImpl extends ServiceImpl<ImMessageMapper, ImMessage>
    implements ImMessageService{

    @Override
    public Result<List<UserWithLastMessageVo>> getUserIdsByWaiterId(Long waiterId) {
        // 从数据库获取与客服交流过的所有用户ID
        Set<Long> userIds = baseMapper.getUserIdsByWaiterId(waiterId);

        // 构建用户ID列表及每个用户的最后一条消息的列表
        List<UserWithLastMessageVo> usersWithLastMessage = new ArrayList<>();
        for (Long userId : userIds) {
            UserWithLastMessageVo userWithLastMessage = new UserWithLastMessageVo();
            userWithLastMessage.setUserId(userId);
            // 获取每个用户的最后一条消息
            ImMessage lastMessage = baseMapper.getLastMessageForUser(userId,waiterId);
            userWithLastMessage.setLastMessage(lastMessage);
            usersWithLastMessage.add(userWithLastMessage);
        }

        return Result.ok(usersWithLastMessage);
    }

    @Override
    public List<ImMessage> getOfflineMessages(Long currentUserId, Long customerId) {
        LambdaQueryWrapper<ImMessage> queryWrapper = new LambdaQueryWrapper<>();


        queryWrapper.and(wrapper -> wrapper
                .eq(ImMessage::getFromId, customerId)
                .eq(ImMessage::getToId, currentUserId)
                .or()
                .eq(ImMessage::getFromId, currentUserId)
                .eq(ImMessage::getToId, customerId)
        );
        return this.list(queryWrapper);
    }
}




